package m.common.netty;

import m.system.netty.NettyClient;
import m.system.netty.NettyMessage;
import m.system.netty.NettyServer;
import m.system.util.SystemUtil;

import java.util.Random;

public class HostNettyUtil {
	private static boolean init=false;
	public static void done() {
		if(!init) {
			try {
				Thread.sleep(100);
			} catch (InterruptedException ignored) {}
			done();
		}
	}
	public static boolean isInit() {
		return init;
	}
	private static boolean isClient=true;
	public static void closeAll() {
		closeClient(false);
		closeServer(false);
	}
	
	private static NettyServer<NettyMessage> server;
	private static NettyClient<NettyMessage> client;
	/**
	 * 开启服务端
	 *  port
	 */
	public static void openServer(int port) {
		if(null==server) {
			server= new NettyServer<>(new HostNettyServerEvent(), port);
			server.setTimerTask(new HostNettyServerTimer(), 10000);
			new Thread(() -> {
                try {
                    server.open();
                } catch (Exception e) {
                    SystemUtil.printlnIf(true,"主机服务启动失败:",e.getMessage());
                    //e.printStackTrace();
                }
            }).start();
		}
	}
	/**
	 * 关闭服务端
	 */
	public static void closeServer(boolean isServer) {
		if((!isServer)&&null!=server) {
			init=true;
			SystemUtil.printlnIf(true,"关闭 服务端");
		}
		if(null!=server) {
			server.close();
			server=null;
		}
	}
	/**
	 * 获取服务
	 * 
	 */
	public static NettyServer<NettyMessage> getServer() {
		return server;
	}
	private static String clientIp;
	private static int clientPort;
	/**
	 * 开启客户端
	 *  ip
	 *  port
	 */
	public static void openClient(String ip,int port) {
		if(null==client) {
			clientIp=ip;
			clientPort=port;
			client= new NettyClient<>(new HostNettyClientEvent(), ip, port);
			client.setTimerTask(new HostNettyClientTimer(), 10000);
			SystemUtil.printlnIf(true,client);
			new Thread() {
				public void run() {
					try {
						if(null!=client)
							client.open();
					} catch (Exception e) {
						SystemUtil.printlnIf(true,"主机客户端启动失败:",e.getMessage());
						HostNettyUtil.reopenClient();
					}
				}
			}.start();
		}
	}
	/**
	 * 关闭客户端
	 */
	public static void closeClient(boolean isClient) {
		if((!isClient)&&null!=client) {
			init=true;
			SystemUtil.printlnIf(true,"关闭 客户端");
			HostNettyUtil.isClient= false;
		}
		if(null!=client) {
			client.close();
			client=null;
		}
	}
	/**
	 * 重启客户端
	 */
	public static void reopenClient() {
		closeClient(isClient);
		if(isClient) {
			try {
				Thread.sleep(5000+new Random().nextInt(5000)); //延迟五秒启动
			} catch (InterruptedException ignored) { }
			SystemUtil.printlnIf(true,"主机客户端重启");
			openClient(clientIp, clientPort);
		}
	}
	/**
	 * 获取客户端
	 * 
	 */
	public static NettyClient<NettyMessage> getClient() {
		return client;
	}
}
